import 'package:easy_refresh/easy_refresh.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:flutter_smart_dialog/flutter_smart_dialog.dart';
import 'package:get/get.dart';
import 'package:sptapp/api/interface/user_api.dart';
import 'package:sptapp/api/request/response_data.dart';
import 'package:sptapp/config/const.dart';
import 'package:sptapp/moudle/common_info.dart';
import 'package:sptapp/moudle/message.dart';
import 'package:sptapp/moudle/refresh/my_refresh.dart';
import 'package:sptapp/widget/common_widget.dart';

class AddDevicePage extends StatefulWidget {
  const AddDevicePage({super.key});

  @override
  State<AddDevicePage> createState() => _AddDevicePageState();
}

class _AddDevicePageState extends State<AddDevicePage> {

  TextEditingController _editingController = TextEditingController();
  List _list = [];
  String sn = '';

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    _getList();
  }

  _getList()async{
    Map<String,dynamic> data = {};
    ResponseData res = await UserAPI.selectEquipment(data);
    if(res.code == 200){
      _list = res.data??[];
    }
    if(mounted){setState(() {});}
  }

  _addDevice()async{
    if(sn == null || sn.isEmpty){
      return;
    }
    Map<String,dynamic> data = {
      'sn': sn
    };
    showLoading();
    ResponseData res = await UserAPI.addDevice(data);
    hideLoading();
    if(res.code == 200){
      _getList();
      getBaseUserInfo((){
         if(baseUserInfo['networkExist'] == false){
          _showNoNetworkAlert();
        }
      });
    }
  }

  _showNoNetworkAlert(){
    SmartDialog.show(
        alignment: Alignment.center,
        builder: (BuildContext ctx){
          return Container(
            decoration: BoxDecoration(
                color: Colors.white,
                borderRadius: BorderRadius.circular(20.w)
            ),
            margin: EdgeInsets.symmetric(horizontal: 30.w),
            padding: EdgeInsets.symmetric(horizontal: 30.w,vertical: 30.w),
            child: Container(
              child: Column(
                mainAxisSize: MainAxisSize.min,
                children: [
                  Container(
                    child: Text(alert_waring_title.tr),
                  ),
                  SizedBox(height: 30.w,),
                  Container(
                    child: Text(home_have_no_network_alert_text.tr),
                  ),
                  SizedBox(height: 30.w,),
                  Container(
                    child: Row(
                      mainAxisAlignment: MainAxisAlignment.spaceAround,
                      children: [
                        GestureDetector(
                          onTap: (){
                            SmartDialog.dismiss();
                          },
                          child: Container(
                            width: 200.w,
                            height: 90.w,
                            alignment: Alignment.center,
                            decoration: BoxDecoration(
                                color: Colors.grey,
                                borderRadius: BorderRadius.circular(20.w)
                            ),
                            child: Text(alert_waring_canclebtn_text.tr),
                          ),
                        ),
                        GestureDetector(
                          onTap: (){
                            SmartDialog.dismiss();
                            Navigator.of(context).pushNamed('DeviceNetPage').then((val){
                              _getList();
                            });
                          },
                          child: Container(
                            width: 200.w,
                            height: 90.w,
                            alignment: Alignment.center,
                            decoration: BoxDecoration(
                                color: themeColor,
                                borderRadius: BorderRadius.circular(20.w)
                            ),
                            child: Text(alert_waring_surebtn_text.tr),
                          ),
                        )
                      ],
                    ),
                  )
                ],
              ),
            ),
          );
        }
    );
  }

  _deleteDevice(item)async{
    Map<String,dynamic> data = {
      'id': item['id']
    };
    showLoading();
    ResponseData res = await UserAPI.deleteDevice(data);
    hideLoading();
    if(res.code == 200){
      _getList();
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: defaultBgColor,
      appBar: myAppBar(context, add_device_page_title.tr),
      body: Container(
        padding: EdgeInsets.symmetric(horizontal: 30.w),
        child: Column(
          children: [
            Container(
              width: 690.w,
              height: 100.w,
              child: Row(
                children: [
                  Expanded(child: Container(
                    padding: EdgeInsets.symmetric(horizontal: 20.w),
                    decoration: BoxDecoration(
                      borderRadius: const BorderRadius.all(Radius.circular(8)),
                      border: Border.all(color: Colors.grey,width: 1)
                    ),
                    child: Container(
                      child: Row(
                        children: [
                          Expanded(child: TextField(
                            //控制器
                            textInputAction: TextInputAction.done,
                            controller: _editingController,
                            maxLines: 1,
                            maxLength: 14,
                            //是否自动更正
                            autocorrect: true,
                            //是否自动对焦
                            autofocus: false,
                            style: TextStyle(
                                color: inputColor,
                                fontSize: 32.sp,
                                fontWeight: FontWeight.w600
                            ),
                            inputFormatters: [
                              FilteringTextInputFormatter.allow(RegExp("[0-9]"))
                            ],
                            decoration: InputDecoration(
                              contentPadding: const EdgeInsets.symmetric(vertical: 0,horizontal: 0),
                              hintText: add_device_hintText.tr,
                              hintStyle: TextStyle(
                                  color: inputColor,
                                  fontSize: 32.sp,
                                  fontWeight: FontWeight.w600
                              ),
                              counterText: "",
                              border: OutlineInputBorder(
                                  borderSide: BorderSide.none),
                            ),
                            onChanged: (val){
                              setState(() {
                                sn = val.trim();
                              });
                            },
                          )),
                          SizedBox(width: 20.w,),
                          Visibility(visible: sn!=null&&sn!.isNotEmpty,
                            child: GestureDetector(
                              onTap: (){
                                setState(() {
                                  _editingController.text = '';
                                  sn = '';
                                });
                              },
                              child: Container(
                                child: Image.asset('assets/login/icon_clear.png',width: 56.w,),
                              ),
                            ),
                          )
                        ],
                      ),
                    )
                  )),
                  SizedBox(width: 20.w,),
                  GestureDetector(
                    onTap: (){
                      _addDevice();
                    },
                    child: Container(
                      alignment: Alignment.center,
                      width: 120.w,
                      height: 90.w,
                      decoration: BoxDecoration(
                          color: sn == null || sn!.isEmpty ? Colors.grey:themeColor,
                          borderRadius: BorderRadius.circular(20.w)
                      ),
                      child: Text(add_device_page_add_btn.tr),
                    ),
                  ),
                  SizedBox(width: 20.w,),
                  GestureDetector(
                    onTap: (){
                      Navigator.of(context).pushNamed('ScanPage').then((val){
                        if(val!= null && val is String){
                           setState(() {
                             _editingController.text = val;
                             sn = val;
                          });
                           _addDevice();
                        }
                      });
                    },
                    child: Container(
                      alignment: Alignment.center,
                      width: 120.w,
                      height: 90.w,
                      decoration: BoxDecoration(
                        color: themeColor,
                        borderRadius: BorderRadius.circular(20.w)
                      ),
                      child: Text(add_device_page_scan_btn.tr),
                    ),
                  ),
                ],
              ),
            ),
            SizedBox(height: 30.w,),
            Expanded(
                child: EasyRefresh(
                  header: myRefreshHeader(),
                  onRefresh: (){
                    _getList();
                  },
                  child: ListView.builder(itemBuilder: (context,index){
                    return Container(
                      width: 690.w,
                      padding: EdgeInsets.symmetric(horizontal: 20.w,vertical: 20.w),
                      decoration: BoxDecoration(
                        color: Colors.white,
                        borderRadius: BorderRadius.circular(20.w)
                      ),
                      margin: EdgeInsets.only(bottom: 30.w),
                      child: Container(
                        child: Row(
                          children: [
                            Container(
                              child: Icon(Icons.circle_outlined),
                            ),
                            SizedBox(width: 10.w,),
                            Container(
                              width: 120.w,
                              height: 120.w,
                              color: Colors.grey,
                            ),
                            SizedBox(width: 20.w,),
                            Expanded(child: Container(
                              child: Column(
                                crossAxisAlignment: CrossAxisAlignment.start,
                                children: [
                                  Text('${add_device_page_item_sn.tr}: ${_list[index]['sn']??''}'),
                                  Text('${add_device_page_item_time.tr}: ${_list[index]['createTime']??''}'),
                                ],
                              ),
                            )),
                            SizedBox(width: 20.w,),
                            Visibility(
                              child: GestureDetector(
                              onTap: (){
                                // setState(() {
                                //   _list.removeAt(index);
                                // });
                                _deleteDevice(_list[index]);
                              },
                              child: Container(
                                child: Icon(Icons.delete),
                              ),
                            ),
                              visible: _list[index]['status'].toString()=='2',
                            )
                          ],
                        ),
                      ),
                    );
                  },itemCount: _list.length,padding: EdgeInsets.zero,),
                )
            )
          ],
        ),
      ),
    );
  }
}
